#! lua

assert(riscos.version,"SearchDir requires RiscLua 5.00 or later")

do
  local sys,dim,dir in riscos
  local throwback = false
  local thisdir = arg[1]
  local textpat = arg[2]
  local recurse = arg[3]

  function searchdir(thisdir,textpat,recurse)
     print(thisdir)
     for leaf,ftype in dir(thisdir) do
     print(leaf)
      local path = thisdir.."."..leaf
      if (ftype == 0x1000) or (ftype == 0x2000) then
        if recurse == "recurse" then
          searchdir(path,textpat,recurse)
        end
      elseif (ftype == 0xffd) or (ftype == 0xfff) then
        local linenumber = 0
        for line in io.lines(path) do
          linenumber = linenumber + 1
          local match = line:find(textpat)
          if match then
            if not throwback then
              sys("DDEUtils_ThrowbackStart")
              throwback = true
            end -- if
            sys("DDEUtils_ThrowbackSend",2,0,dim(path),linenumber,0,dim(line))
          end -- if
        end -- for
      end -- if
    end -- for
  end -- function

  searchdir(thisdir,textpat,recurse)
  if throwback then
    sys("DDEUtils_ThrowbackEnd")
  else
    sys("OS_CLI",dim("Sound 1 &fff5 &5000 10"))
  end -- if
end -- do

